//
//  File.swift
//  Fiveo
//
//  Created by 张朋朋 on 12/16/24.
//

import Foundation
import AgoraInfra_iOS
import AgoraRtcKit
import CommonBasicModule
import UMengSDK
import Log
protocol RtcProtocol: AnyObject {
    func rtcEngine(uid: Int, isSpeaking: Bool, totalVolume: Int)

}
class RtcManager: NSObject {
    static let share: RtcManager = RtcManager()
    private(set) var agoraKit: AgoraRtcEngineKit?
    weak var delegate: RtcProtocol?
    private var isInRoom: Bool = false
    public func sharedEngine(withAppId: String) { //"6cafc1444b5141c4a942c41290f602af"
        agoraKit = AgoraRtcEngineKit.sharedEngine(withAppId:withAppId, delegate: self)
        agoraKit?.enableAudio()
        agoraKit?.enableVideo()
        let videoConfig = AgoraVideoEncoderConfiguration()
        videoConfig.codecType = .H264 //设置编码放过和i
        let height = (CGFloat.screenHeight / CGFloat.screenWidth) * 720
        videoConfig.dimensions = CGSize(width: 720, height: height.int)
//        videoConfig.mirrorMode = .auto
//        videoConfig.frameRate = .fps30
        agoraKit?.setParameters("{\"che.audio.aiaec.working_mode\": 2}")
        agoraKit?.setParameters("{\"che.audio.agc.enable\":false}")  // 关闭增益控制
        agoraKit?.setAINSMode(true, mode: AUDIO_AINS_MODE.AINS_MODE_ULTRALOWLATENCY)
        agoraKit?.setAudioScenario(.gameStreaming)// 实现高音质直播
        agoraKit?.adjustRecordingSignalVolume(20)
        agoraKit?.setVideoEncoderConfiguration(videoConfig)
        agoraKit?.enableAudioVolumeIndication(200, smooth: 3, reportVad: true)
        let config = AgoraCameraCapturerConfiguration()
        config.cameraDirection = .rear
        agoraKit?.setCameraCapturerConfiguration(config)
    }
}
extension RtcManager {
    
    func startPreview(localView: UIView) {
        // 启用视频模块
        agoraKit?.enableLocalVideo(true)
        agoraKit?.enableVideo()
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.view = localView
        videoCanvas.renderMode = .hidden
        // 设置本地视图
        agoraKit?.setupLocalVideo(videoCanvas)
        // 开始本地视频预览
        agoraKit?.startPreview()
    }
    func startAudio() {
        MHLog.log("打开音频")
        // 开始本地音频
//        agoraKit?.muteLocalAudioStream(false)
        agoraKit?.enableLocalAudio(true)
        agoraKit?.enableAudio()
        agoraKit?.adjustRecordingSignalVolume(20)
       
    }
    // 切换前置/后置摄像头。
    func switchCamera() {
        MHLog.log("切换摄像头")
        agoraKit?.switchCamera()
    }
    //    结束本地音频预览
    func disRecording() {
        MHLog.log("静音")
       agoraKit?.adjustRecordingSignalVolume(0)
    }
    //    结束本地音频预览
    func stopAudio() {
        MHLog.log("静音")
        agoraKit?.enableLocalAudio(false)
        agoraKit?.disableAudio()
//        agoraKit?.adjustRecordingSignalVolume(0)
//        agoraKit?.muteLocalAudioStream(true)
    }
    //    结束本地视频预览
    func stopPreview() {
        agoraKit?.enableLocalVideo(false)
        agoraKit?.stopPreview()
        agoraKit?.disableVideo()
    }
    // 退出房间
    func leaveChannel( block: (() -> Void)?) {
        if !isInRoom {
            block?()
            return
        }
        MHLog.log("将要离开房间")
        agoraKit?.leaveChannel({ [weak self] stats in
            MHLog.log("已经离开房间")
            self?.isInRoom = false
            block?()
        })
    }
    //    销毁引擎，并释放声网 SDK 中使用的所有资源。
    func destroy() {
        
        AgoraRtcEngineKit.destroy()
    }
    func setCameraTorchOn(on: Bool) {
        agoraKit?.setCameraTorchOn(on)
    }
    //    销毁引擎，并释放声网 SDK 中使用的所有资源。
    func setCameraFocusPositionInPreview(point: CGPoint) {
        guard let agoraKit = agoraKit else { return  }
        if agoraKit.isCameraFocusPositionInPreviewSupported() {
            agoraKit.setCameraFocusPositionInPreview(point)
        }
       
    }
    //    加入频道并发布音视频流
    func joinChannelByTokenAudio(byToken: String, channelId: String, uid: Int, cameraTrack: Bool) {
        isInRoom = true
        let options = AgoraRtcChannelMediaOptions()
        // 设置频道场景为直播
        options.channelProfile = .liveBroadcasting
        // 设置用户角色为主播；如果要将用户角色设置为观众，保持默认值即可
        options.clientRoleType = .broadcaster
        
        // 发布麦克风采集的音频
        options.publishMicrophoneTrack = true
        // 发布摄像头采集的视频
        options.publishCameraTrack = cameraTrack
        // 自动订阅所有音频流
        options.autoSubscribeAudio = true
        // 自动订阅所有视频流
        options.autoSubscribeVideo = true
        // 使用临时 Token 加入频道，在这里传入你的项目的 Token 和频道名
        // uid 为 0 表示由引擎内部随机生成; 成功后会触发 didJoinChannel 回调
        agoraKit?.joinChannel(byToken: byToken, channelId: channelId, uid: UInt(uid), mediaOptions: options)
        
    }
}
extension RtcManager: AgoraRtcEngineDelegate {
    
    /// 在SDK运行时发生错误
    /// - Parameters:
    ///   - engine: 引擎AgoraRtcEngineKit对象
    ///   - errorType:  errorCode AgoraErrorCode 当初始化调用失败时，SDK报告AgoraErrorCodeStartCall = 1002错误
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOccur errorType: AgoraEncryptionErrorType) {
        MHLog.log("发生错误 errorType: \(errorType)")
        UMEvent.makeEvent(id: "Audiocall_Link_Fail",attributes: ["reasons":"发生错误 errorType: \(errorType)"])
    }
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) {
        //        setupRemoteVideo(uid: uid)
    }
    // 成功加入频道回调
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int) {
        MHLog.log("didJoinChannel: \(channel), uid: \(uid)")
    }
    // 远端用户或主播离开当前频道回调
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) {
        MHLog.log("didOfflineOfUid uid: \(uid)")
    }
    func rtcEngine(_ engine: AgoraRtcEngineKit, activeSpeaker speakerUid: UInt) { //监测到远端最活跃用户回调。
        
        MHLog.log("监测到远端最活跃用户回调\(speakerUid)")
    }
    func rtcEngine(_ engine: AgoraRtcEngineKit, firstLocalAudioFramePublished elapsed: Int) { //已发布本地音频首帧回调。
        MHLog.log("已发布本地音频首帧回调。\(elapsed)")
        
    }
    func rtcEngine(_ engine: AgoraRtcEngineKit, didAudioMuted muted: Bool, byUid uid: UInt) { //远端用户（通信场景）/主播（直播场景）停止或恢复发送音频流回调。
        MHLog.log("远端用户（通信场景）/主播（直播场景）停止或恢复发送音频流回调。muted:\(muted) uid:\(uid)")
    }
    func rtcEngine(_ engine: AgoraRtcEngineKit, reportAudioVolumeIndicationOfSpeakers speakers: [AgoraRtcAudioVolumeInfo], totalVolume: Int) {
        for speaker in speakers {
            if speaker.uid != 0 {
                let volume = speaker.volume
                if volume > 0 {
                    delegate?.rtcEngine(uid: Int(speaker.uid), isSpeaking: true, totalVolume: Int(volume))
                } else {
                    delegate?.rtcEngine(uid: Int(speaker.uid), isSpeaking: false, totalVolume: Int(volume))
                }
            }
        }
    }
    
}


